package com.wctj.api.base.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.tuple.Pair;

@Slf4j
public class PinyinUtil {

    /**
     * 获取名称的拼音及拼音简写
     *
     * @param name 汉字名称
     * @return 包含拼音和拼音简写的字符串数组
     */
    public static Pair<String,String> getNamePinyinAndShort(String name) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调
//        format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 小写
        
        StringBuilder pinyin = new StringBuilder();
        StringBuilder shortPinyin = new StringBuilder();
        char[] chars = name.toCharArray();
        for (char c : chars) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { // 判断是否为汉字字符
                try {
                    String py = PinyinHelper.toHanyuPinyinStringArray(c,format)[0]; // 取第一个拼音
                    pinyin.append(py);
                    shortPinyin.append(py.charAt(0));
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyin.append(c);
                shortPinyin.append(c);
            }
        }
        return Pair.of(pinyin.toString(), shortPinyin.toString());
    }

    public static void main(String[] args) {
        String name = "张三丰";
        Pair<String,String>  result = getNamePinyinAndShort(name);
        log.info("全拼: " + result.getLeft());
        log.info("简拼: " + result.getRight());
    }
}
    